<template>
  <el-dialog
    custom-class="cancel-staff-reim"
    v-el-drag-dialog="{ drag: true, full: true, resize: false }"
    :close-on-click-modal="false"
    :visible="true"
    @close="closeMd"
    width="80%"
    title="报账核销"
    append-to-body>
    <div ref="dgtools" class="filter-container">
      <div class="dgts-row">
        <el-form 
          :model="fm.ps" 
          :ref="fm.fname"
          :inline="true"
          style="margin-right: 20px;">
          <el-form-item label="入账月份">
            <el-date-picker 
              v-model="fm.ps.enterMonth" 
              type="month" 
              placeholder="入账月份"
              value-format="yyyy-MM-dd"
              style="width: 120px;"
            />
          </el-form-item>

          <el-button 
            type="primary" 
            icon="el-icon-success" 
            :loading="fm.sb.load"
            @click="onSubmit">
            {{fm.sb.text}}
          </el-button>
        </el-form>

        <div class="dgts-text-tj1">
          <b class="tr-it c-green">累计</b>
          <el-divider direction="vertical"></el-divider>
          <span class="tr-it c-green">收入：{{dg.totalGath}} 元</span>
          <el-divider direction="vertical"></el-divider>
          <span class="tr-it c-red">支出：{{dg.totalPay}} 元</span>
          <el-divider direction="vertical"></el-divider>
          <span class="tr-it c-yellow">收支差额：{{dg.totalBalance}} 元</span>
        </div>

        <div class="dgts-text-tj2">
          <b class="tr-it c-green">所选</b>
          <el-divider direction="vertical"></el-divider>
          <span class="tr-it c-green">收入：{{seledGath}} 元</span>
          <el-divider direction="vertical"></el-divider>
          <span class="tr-it c-red">支出：{{seledPay}} 元</span>
          <el-divider direction="vertical"></el-divider>
          <span class="tr-it c-yellow">收支差额：{{seledBalance}} 元</span>
        </div>
      </div>

      <el-divider></el-divider>

      <div class="dgts-row">
        <el-form 
          :model="dg.ps" 
          :inline="true"
          @keyup.enter.native="getDgList">
          <el-form-item>
            <el-select 
              v-model="dg.ps.timeType" 
              placeholder="时间类型"
              style="width: 100px;">
              <el-option label="添加时间" value="0"></el-option>
              <el-option label="发生时间" value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="dg.ps.sedate"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              style="width: 210px;"
            />
          </el-form-item>

          <el-form-item>
            <el-input 
              placeholder="交易金额" 
              clearable 
              maxlength="6"
              v-model="dg.ps.findMoney" 
              style="width: 120px;"
            />
          </el-form-item>

          <el-form-item>
            <el-select 
              v-model="dg.ps.moneyType" 
              placeholder="金额类型" 
              clearable
              style="width: 150px;">
              <el-option
                v-for="item in moneyOptions"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-input 
              placeholder="对方户名" 
              clearable 
              v-model="dg.ps.transName"
              style="width: 120px;"
            />
          </el-form-item>

          <el-form-item>
            <el-input 
              placeholder="摘要" 
              clearable 
              v-model="dg.ps.remark"
            />
          </el-form-item>

          <el-form-item>
            <el-button 
              type="primary" 
              icon="el-icon-search" 
              @click="getDgList">
              搜索
            </el-button>
          </el-form-item>
          
        </el-form>
      </div>
    </div>

    <el-table
      :ref="dg.tbName"
      :data="dg.list"
      row-key="id"
      :height="bodyHeight"
      border fit 
      :row-class-name="rowClassName"
      @header-dragend="dragHeader"
      @selection-change="selRowChange">
      <el-table-column 
        fixed="left" 
        type="index" 
        label="编号"
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>
      <el-table-column 
        fixed="left" 
        type="selection" 
        align="center" 
        :resizable="false" 
        width="40">
      </el-table-column>
      <el-table-column 
        v-for="(col, index) in dg.columns" 
        :key="index"
        :class-name="dg.dgName"
        :prop="col.field"
        :label="col.label"
        :width="col.width">
        <template slot-scope="{row}">
          <template v-if="col.field == 'tradeTime'">
            {{row.tradeTime | time('yyyy年MM月dd号 HH:mm')}}
          </template>

          <template v-else-if="col.field == 'isCheck'">
            <span v-if="row.isCheck == '-1'" class="c-bbb">已结算</span>
            <span v-else-if="row.isCheck == '0'" class="c-red">未操作</span>
            <span v-else class="c-green">已报销</span>
          </template>

          <template v-else>{{ getColVal(row, col.field) }}</template>
        </template>
      </el-table-column>
    </el-table>
    <Pagination 
      v-show="dg.total > 0" 
      :total="dg.total" 
      :page.sync="dg.ps.page" 
      :limit.sync="dg.ps.rows" 
      @pagination="getDgList"
    />

  </el-dialog>
</template>

<script>
import DataGridResize from '@/views/mixins/DataGridResize';
import DataGridBase from "@/views/mixins/DataGridBase";
import elDragDialog from "@/directive/el-drag-dialog";
import Pagination from '@/components/Pagination';

import * as commonSer from "@/api/services/common.service";
import * as orderSer from "@/api/services/order.service";

export default {
  name: "CancelStaffReim",
  mixins: [DataGridResize, DataGridBase],
  directives: {elDragDialog},
  props: {myData: Object},
  components: {Pagination},
  data() {
    let cols = [
      {label: '交易时间', field: 'tradeTime', width: 140},
      {label: '金额类型', field: 'moneyTypeId.typeName', width: 150},
      {label: '银行名称', field: 'myBankName', width: 'auto'},
      {label: '报销状态', field: 'isCheck', width: 'auto'},
      {label: '对方户名', field: 'transName', width: 100},
      {label: '借', field: 'tradeInMoney', width: 80},
      {label: '贷', field: 'tradeOutMoney', width: 80},
      {label: '余额', field: 'balance', width: 80},
      {label: '摘要', field: 'remark', width: 150},
    ];
    return {
      dg: {
        dgName: 'dg',
        tbName: 'cancelStaffReimTb',
        total: 0,
        list: [],
        srcCols: cols,
        columns: [],
        selRows: [],
        ps: {
          page: 1, rows: 20,
          // 收支情况 eg:0收入 1支出
          status: 0,
          // 起止日期
          sedate: [],
          // 审核状态
          isCheck:'0',
          // 时间类型
          timeType: '0',
          // 交易金额
          findMoney: '', 
          // 对方户名
          transName: '', 
          // 金额类型
          moneyType: '', 
          // 摘要
          remark: '',  
        },
        // 员工报账-累计收入
        totalGath: 0,
        // 员工报账-累计支出 
        totalPay: 0,
        // 员工报账-累计收支差额 
        totalBalance: 0, 
      },

      fm: {
        fname: "cancelStaffReimFm",
        sb: { load: false, text: '确定核销' },
        ps: {
          // 入账月份
          enterMonth: '',
        },
      },
      // 金额类型-列表
      moneyOptions: []
    };
  },
  computed: {
    // 银行记账-所选收入
    seledGath(){
      let money = 0, rows = this.getSeledRows();
      rows.forEach(it => {money += parseFloat(it.tradeInMoney);});
      return (money).toFixed(2);
    },
    // 银行记账-所选支出
    seledPay(){
      let money = 0, rows = this.getSeledRows();
      rows.forEach(it => {money += parseFloat(it.tradeOutMoney);});
      return (money).toFixed(2);
    },
    // 银行记账-所选收支差额
    seledBalance(){
      let money = 0, rows = this.getSeledRows();
      rows.forEach(it => {money += Math.abs(parseFloat(it.tradeInMoney) - parseFloat(it.tradeOutMoney));});
      return (money).toFixed(2);
    },
  },
  created() {
    const that = this;

    // 需要放到getDgList方法前面
    that.init();

    that.initTbSetData(that.dg.dgName);
    that.getDgList();
  },
  methods: {
    closeMd() {
      this.$emit("myClick", {state: false});
    },
    init() {
      const that = this;

      console.log('员工报账记录：', that.myData.list);

      // 统计数据
      let totalGath = 0, totalPay = 0, totalBalance = 0;
      that.myData.list.forEach(it => {
        // 累计收入
        totalGath += parseFloat(it.gathMoney);
        // 累计支出
        totalPay += parseFloat(it.payMoney);
        // 收支差额
        totalBalance += Math.abs(parseFloat(it.gathMoney) - parseFloat(it.payMoney));
      });
      that.dg.totalGath = (totalGath).toFixed(2);
      that.dg.totalPay = (totalPay).toFixed(2);
      that.dg.totalBalance = (totalBalance).toFixed(2);

      // 获取-金额类型列表
      commonSer.getMoneyTypeDict().then(res => {
        that.moneyOptions = res.mTypes;
      });
    },

    // 获取-表格列表
    getDgList(){
      const that = this, U = that.U, dg = that.dg, ps = U.scopy(dg.ps);
      
      ps.sTime = (ps.sedate && ps.sedate.length == 2) ? ps.sedate[0] : '';
      ps.eTime = (ps.sedate && ps.sedate.length == 2) ? ps.sedate[1] : '';
      delete ps.sedate;

      // 0-收入 1-支出
      ps.status = that.dg.totalGath > that.dg.totalPay ? 0 : 1;

      orderSer.getBankTradeList(ps).then(res => {
        if(res.code == 1){
          let list = res.data;
          list.forEach(it => {it.dgName = dg.dgName;});
      
          dg.list = list;
          dg.total = res.count;
        }
      });
    },
    
    // 确定核销
    onSubmit() {
      const that = this, U = that.U, fm = that.fm, sb = fm.sb, ps = U.scopy(fm.ps), rows = that.getSeledRows();

      if(rows.length === 0) {
        U.qerror("请选择要核销的记录");
      }else{
        if(!ps.enterMonth){
          U.qerror('请选择入账月份');
        }else if(!that.myData.list || that.myData.list.length == 0){
          U.qerror('您未选择报账记录，请关闭弹框重新选择报账记录');
        }else if(that.myData.list.length > 1 && rows.length > 1){
          U.qerror('您有多条报账记录，只能选择1条核销记录');
        }else{
          // 银行账记录id,多条逗号拼接
          ps.btlIds = rows.map(it => it.id).join(',');
          // 员工报账记录id,多条逗号拼接
          ps.srIds = that.myData.list.map(it => it.id).join(',');

          sb.load = true;
          orderSer.cancellationStaffReim(ps).then(res => {
            sb.load = false;

            if (res.code !== 1) {
              U.qerror(res.msg);
            }else{
              U.qsuccess(res.msg);

              that.closeMd();
              that.$emit("reloadDg");
            }
          });
        }
      }
    },

    

  },
};
</script>
<style lang="less" scoped>
.cancel-staff-reim{
  .el-divider--horizontal{
    margin: 10px 0px !important;
  }
}
</style>